<template>
  <div class="index">
    <!--Hero Section-->
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">呼吸之間<span>·</span>皆是自在</h1>
        <h2 class="hero-subtitle">現代简约线条，勾勒理想之家</h2>
        <h2 class="hero-subtitle">精选天然材质，诠释生活美学</h2>
        <TheButton @click="goToCategory('')" size="large" class="dark-bg hero-btn">
          前往商城
        </TheButton>
      </div>
      <img src="~/assets/images/hero.png" alt="Comfortable armchair" />
    </div>
    <div class="content-wrapper">
      <!--熱門商品橫向輪播-->
      <div class="popular-products-section">
        <div class="container">
          <div class="header acea-row row-center-wrapper">
            <div class="lines"></div>
            <div class="name">熱門商品</div>
            <div class="lines"></div>
          </div>
        </div>
        <div class="products-scroll">
          <div v-if="
            classifyList.length > 0 &&
            classifyList[0].productList &&
            classifyList[0].productList.length > 0
          " class="carousel-container" @mouseenter="pauseCarousel" @mouseleave="resumeCarousel">
            <div class="carousel-track" :style="{ transform: `translateX(${carouselOffset}px)` }">
              <!-- 原始商品 -->
              <div v-for="(product, index) in classifyList[0].productList.slice(
                0,
                8
              )" :key="`original-${product.id || index}`" class="carousel-item">
                <ProductCard :product="product" @click="goDetail" style="cursor: pointer" />
              </div>
              <!-- 複製商品用於無縫循環 -->
              <div v-for="(product, index) in classifyList[0].productList.slice(
                0,
                8
              )" :key="`clone-${product.id || index}`" class="carousel-item">
                <ProductCard :product="product" @click="goDetail" style="cursor: pointer" />
              </div>
            </div>
          </div>
          <div v-else class="loading-container">
            <p>加載中...</p>
          </div>
        </div>
      </div>

      <!--家具展示網格-->
      <div class="furniture-grid-section">
        <div class="header acea-row row-center-wrapper">
          <div class="lines"></div>
          <div class="name">精選家具</div>
          <div class="lines"></div>
        </div>
        <div class="furniture-grid">
          <div class="grid-image-left">
            <img src="~/assets/images/b003.png" alt="臥室家具" />
          </div>
          <div class="grid-content-left">
            <h3>臥室家具</h3>
            <div class="grid-text">
              <p>年度銷冠床架 萬組家庭見證品質</p>
              <p>北歐風格設計 自然舒適睡眠體驗</p>
              <p>国际认证环保材质 居家健康首选</p>
            </div>
            <TheButton class="grid-btn" @click="goToCategory('bedroom')">
              立即選購
            </TheButton>
          </div>
          <div class="grid-content-right">
            <h3>客廳家具</h3>
            <div class="grid-text">
              <p>万件商品一站购足 满足所有家具需求</p>
              <p>从客厅到卧室 完整您的居家配置</p>
              <p>多种风格任您挑选 打造梦想家园</p>
            </div>
            <TheButton class="grid-btn" @click="goToCategory('living')">
              立即選購
            </TheButton>
          </div>
          <div class="grid-image-right">
            <img src="~/assets/images/b004.png" alt="客廳家具" />
          </div>
        </div>
      </div>

      <!--新品首发模块-->
      <div class="new-products">
        <div class="header acea-row row-center-wrapper">
          <div class="lines"></div>
          <div class="name">新品首发</div>
          <div class="lines"></div>
        </div>
        <div class="products-grid">
          <ProductCardHover v-for="(item, index) in classifyList.length > 0 &&
            classifyList[0].productList
            ? classifyList[0].productList.slice(0, 8)
            : []" :key="index" :product="item" @click="goDetail" />
        </div>
      </div>

      <!--分類-->
      <div class="classify">
        <div class="container">
          <div class="list" v-for="(item, index) in classifyList" :key="index">
            <!--推广横幅 - 热销商品-->
            <div class="promotion-banner" v-if="index === 0 && item.big_pic">
              <div class="wrapper_1200">
                <div class="banner-item">
                  <nuxt-link :to="{
                    path: '/goods_cate',
                    query: { cid: item.id, cidIndex: index },
                  }" class="banner-link">
                    <div class="banner-image">
                      <img :src="item.big_pic" />
                    </div>
                    <div class="banner-content">
                      <h3>{{ item.cate_name }}</h3>
                      <div class="banner-text">
                        <p>年度銷冠沙發 萬組家庭見證品質</p>
                        <p>北歐風模塊沙發 自由組合限時特價</p>
                        <p>国际认证环保材质 居家健康首选</p>
                        <p>全馆家具限时特惠 精选品牌滿減</p>
                      </div>
                      <span class="shop-btn">立即選購</span>
                    </div>
                  </nuxt-link>
                </div>
              </div>
            </div>
            <!--推广横幅 - 全部商品-->
            <div class="promotion-banner" v-if="index === 1 && item.big_pic">
              <div class="wrapper_1200">
                <div class="banner-item">
                  <nuxt-link :to="{
                    path: '/goods_cate',
                    query: { cid: item.id, cidIndex: index },
                  }" class="banner-link">
                    <div class="banner-content">
                      <h3>{{ item.cate_name }}</h3>
                      <div class="banner-text">
                        <p>万件商品一站购足 满足所有家具需求</p>
                        <p>从客厅到卧室 完整您的居家配置</p>
                        <p>大小户型都适合 精选空间解决方案</p>
                        <p>多种风格任您挑选 打造梦想家园</p>
                      </div>
                      <span class="shop-btn">立即選購</span>
                    </div>
                    <div class="banner-image">
                      <img :src="item.big_pic" />
                    </div>
                  </nuxt-link>
                </div>
              </div>
            </div>

            <div class="title acea-row">
              <div class="name">{{ item.cate_name }}</div>
              <nuxt-link :to="{
                path: '/goods_cate',
                query: { cid: item.id, cidIndex: index },
              }" class="more">
                更多
              </nuxt-link>
            </div>
            <div class="acea-row">
              <ProductCard v-for="(itemn, indexn) in item.productList" :key="indexn" :product="itemn"
                @click="goDetail" />
            </div>
          </div>
        </div>
        <div class="loadingicon acea-row row-center-wrapper" v-if="classifyList.length && classifyList.length >= limit">
          <span class="loading iconfont icon-jiazai" v-if="!pullRefreshss"></span>{{ title }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ProductCard from "@/components/ProductCard";
import TheButton from "@/components/TheButton";
import ProductCardHover from "@/components/ProductCardHover";

export default {
  name: "index",
  auth: false,
  components: {
    ProductCard,
    TheButton,
    ProductCardHover,
  },
  data() {
    return {
      classifyList: [], //初始數據代碼
      pullRefreshss: true,
      page: 1, //代表页面的初始页数
      limit: 3,
      scollY: null, // 离底部距离有多少
      pageTotal: 0, //總页数
      title: "下拉加載更多",
      siteName: "",
      dragInitialized: false,
      // 輪播相關數據
      carouselOffset: 0,
      carouselTimer: null,
      carouselSpeed: 1, // 每次移動的像素
      carouselItemWidth: 404, // 每個商品卡片的寬度（380px + 24px gap）
      isPaused: false,
    };
  },

  async asyncData({ app }) {
    let indexMsg = await app.$axios.get("/index");
    return {
      siteName: indexMsg.data.site_name,
    };
  },
  fetch({ store }) {
    store.commit("isHeader", true);
    store.commit("isFooter", true);
  },
  head() {
    return {
      title: this.siteName,
    };
  },
  created() {
    this.getClassifyList();
    // this.$store.commit('logo', this.logoUrl);
    // this.$cookies.set('logo',this.logoUrl);
  },
  mounted() {
    this.pullRefresh();
    // 确保页面滚动到顶部
    this.$nextTick(() => {
      window.scrollTo(0, 0);
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
    });
    // 檢查classifyList數據結構並確保輪播圖初始化
    setTimeout(() => {
      if (this.classifyList.length > 0) {
        console.log("ClassifyList[0]:", this.classifyList[0]);
        console.log("ProductList:", this.classifyList[0].productList);

        // 強制更新視圖，確保swiper正確初始化
        this.$nextTick(() => {
          this.$forceUpdate();
          console.log("Swiper視圖已更新");
          // 避免重複初始化拖動滾動功能
          if (!this.dragInitialized) {
            this.initDragScroll();
            this.dragInitialized = true;
          }

          // 啟動輪播
          this.startCarousel();

          // 再次強制更新，確保輪播圖顯示
          setTimeout(() => {
            this.$forceUpdate();
            console.log("再次強制更新視圖");
          }, 500);
        });
      }
    }, 1000);
  },
  beforeDestroy() {
    window.onscroll = null;
    // 清理輪播定時器
    this.stopCarousel();
  },
  methods: {
    getClassifyList() {
      let _this = this,
        currentPage = { page: this.page, limit: this.limit };
      _this.$axios
        .get("/pc/get_category_product", {
          params: currentPage,
        })
        .then(function (res) {
          _this.pageTotal = res.data.count;
          // 请求完成后，把得到的數據拼接到当前dom里面
          _this.classifyList = _this.classifyList.concat(res.data.list);

          // 數據加載完成後，強制更新視圖，確保swiper正確初始化
          _this.$nextTick(() => {
            _this.$forceUpdate();
            console.log("數據加載完成，視圖已更新");
            // 避免重複初始化拖動滾動功能
            if (!_this.dragInitialized) {
              _this.initDragScroll();
              _this.dragInitialized = true;
            }
          });
        })
        .catch(function (err) {
          _this.$message.error(err);
        });
    },

    initDragScroll() {
      // 設置基本滾動行為
      const scrollContainer = document.querySelector(".scroll-container");
      if (!scrollContainer) return;

      // 設置滾動容器樣式
      scrollContainer.style.cursor = "grab";
      scrollContainer.style.scrollBehavior = "smooth";

      // 禁用框選文本
      scrollContainer.style.userSelect = "none";

      // 實現按住拖動滑動
      let isDown = false;
      let startX;
      let scrollLeft;

      scrollContainer.addEventListener("mousedown", (e) => {
        isDown = true;
        scrollContainer.style.cursor = "grabbing";
        startX = e.pageX - scrollContainer.offsetLeft;
        scrollLeft = scrollContainer.scrollLeft;
        // 防止點擊事件觸發
        e.preventDefault();
      });

      scrollContainer.addEventListener("mouseleave", () => {
        isDown = false;
        scrollContainer.style.cursor = "grab";
      });

      scrollContainer.addEventListener("mouseup", () => {
        isDown = false;
        scrollContainer.style.cursor = "grab";
      });

      scrollContainer.addEventListener("mousemove", (e) => {
        if (!isDown) return;
        e.preventDefault();
        const x = e.pageX - scrollContainer.offsetLeft;
        const walk = (x - startX) * 2; // 滾動速度
        scrollContainer.scrollLeft = scrollLeft - walk;
      });
    },

    // 下拉加載ajax
    pullRefresh: function () {
      let _this = this;
      window.onscroll = function () {
        _this.scrollChange();
      };
    },
    scrollChange: function () {
      var _this = this;
      this.scollY =
        this.comsys.getScrollTop() +
        this.comsys.getWindowHeight() -
        this.comsys.getScrollHeight();
      // 把下拉刷新置為false，防止多次请求
      if (this.scollY >= -50) {
        if (this.page > Math.ceil(this.pageTotal / this.limit)) {
          this.title = "已没有更多數據";
          this.pullRefreshss = true;
          return false;
        }
        if (!this.pullRefreshss) {
          return false;
        }
        _this.pullRefreshss = false;
        this.title = "正在加載中....";
        // 加页碼数
        this.page++;
        _this.getClassifyList();
      } else {
        // 其他时候把下拉刷新置為true
        _this.pullRefreshss = true;
        this.title = "下拉加載更多";
      }
    },
    goDetail(item) {
      let path = item.presale
        ? (path = {
          path: "/goods_presell_detail",
          query: {
            id: item.id,
          },
        })
        : (path = { path: `/goods_detail/${item.id}` });
      this.$router.push(path);
    },

    // 跳轉到分類頁面
    goToCategory(category) {
      this.$router.push({
        path: "/goods_cate",
        query: { category: category },
      });
    },

    // 輪播控制方法
    startCarousel() {
      if (this.carouselTimer) {
        clearInterval(this.carouselTimer);
      }

      this.carouselTimer = setInterval(() => {
        if (!this.isPaused) {
          this.carouselOffset -= this.carouselSpeed;

          // 計算單組商品的總寬度
          const originalItems = this.classifyList[0].productList.length;
          const singleSetWidth = originalItems * this.carouselItemWidth; // carouselItemWidth已包含gap

          if (Math.abs(this.carouselOffset) >= singleSetWidth) {
            this.carouselOffset += singleSetWidth;
          }
        }
      }, 16); // 約60fps
    },
    pauseCarousel() {
      this.isPaused = true;
    },
    resumeCarousel() {
      this.isPaused = false;
    },
    stopCarousel() {
      if (this.carouselTimer) {
        clearInterval(this.carouselTimer);
        this.carouselTimer = null;
      }
    },

    // 獲取新品首發數據
    getNewProducts() {
      let _this = this;
      this.$axios
        .get("/product/hot")
        .then(function (res) {
          _this.newProductsList = res.data.list || [];
          console.log("新品首發數據獲取成功:", _this.newProductsList);
        })
        .catch(function (err) {
          console.error("新品首發數據獲取失敗:", err);
          _this.$message.error("新品首發數據加載失敗");
        });
    },
  },
};
</script>

<style scoped lang="scss">
.index {
  transition: background-color 0.3s ease;

  .hero-section {
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;
    position: relative;

    .hero-content {
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 0 100px;
      transition: background-color 0.3s ease, color 0.3s ease;

      .hero-title {
        font-family: "Cormorant", sans-serif;
        font-size: 4rem;
        font-weight: bold;
        line-height: 1.2;
        color: $obsidian;
        margin-bottom: 3rem;

        span {
          font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
          font-size: 5rem;
          color: $dark-gold;
          margin: 0 20px 10px 20px;
        }
      }

      .hero-subtitle {
        font-family: "Cormorant", sans-serif;
        font-size: 2rem;
        color: $charcoal;
        margin-bottom: 1rem;
        letter-spacing: 2px;
      }

      .hero-btn {
        margin-top: 2rem;
        padding: 12px 20px;
        align-self: flex-start;
        width: auto;
        max-width: 200px;
      }
    }

    img {
      max-width: 100%;
      max-height: 80%;
      object-fit: contain;
      position: absolute;
      right: 2rem;
      bottom: 2rem;
      z-index: 2;
      opacity: 1;
    }
  }

  .content-wrapper {
    padding-top: 100px;

    .popular-products-section,
    .category-section,
    .furniture-grid-section {
      margin-bottom: 80px;

      .header {
        margin-bottom: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 20px;

        .lines {
          width: 80px;
          height: 2px;
          background: linear-gradient(90deg,
              transparent 0%,
              $gold-accent 50%,
              transparent 100%);
        }

        .name {
          font-size: 32px;
          font-weight: 700;
          color: $gold-accent;
          letter-spacing: 2px;
          text-align: center;
          position: relative;
          padding: 0 20px;

          &::before,
          &::after {
            content: "";
            position: absolute;
            top: 50%;
            width: 6px;
            height: 6px;
            background: $gold-accent;
            border-radius: 50%;
            transform: translateY(-50%);
          }

          &::before {
            left: 0;
          }

          &::after {
            right: 0;
          }
        }
      }
    }

    .popular-products-section {
      .container {
        padding: 0 100px;
      }

      .products-scroll {
        position: relative;
        min-height: 380px;
        overflow: hidden;

        .carousel-container {
          width: 100%;
          overflow: hidden;
          padding: 20px 0;

          .carousel-track {
            display: flex;
            gap: 24px;
            will-change: transform;

            .carousel-item {
              flex: 0 0 380px;
              height: auto;
            }
          }
        }

        .loading-container {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 300px;
          width: 100%;
          background-color: rgba($pure-white, 0.8);
          border-radius: 8px;

          p {
            font-size: 18px;
            color: $gold-accent;
          }
        }
      }

      .view-all-container {
        display: flex;
        justify-content: flex-end;
      }
    }

    .furniture-grid-section {
      padding: 0 100px;
      padding-bottom: 80px;
      margin-bottom: 0;

      .row-center-wrapper {
        margin-bottom: 50px;
      }

      .furniture-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-template-rows: 600px 600px;

        .grid-content-left,
        .grid-content-right {
          flex: 1;
          padding: 40px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          gap: 30px;

          h3 {
            font-size: 3rem;
            font-weight: 700;
            text-align: center;
            color: $obsidian;
            margin-bottom: 20px;
          }

          .grid-text {
            margin-bottom: 30px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            gap: 15px;

            p {
              font-size: 22px;
              color: $ivory;
              line-height: 1.5;
            }
          }

          .grid-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 12px 24px;
          }
        }
      }

      .grid-image-left,
      .grid-image-right {
        flex: 0 0 50%;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.5s ease;
        }
      }

      @media (max-width: 992px) {
        grid-template-columns: 1fr;
        grid-template-rows: auto auto auto auto;
      }
    }

    // 新品首发模块样式
    .new-products {
      width: 100%;
      margin-bottom: 100px;

      .header {
        margin-bottom: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 20px;

        .lines {
          width: 80px;
          height: 2px;
          background: linear-gradient(90deg,
              transparent 0%,
              $gold-accent 50%,
              transparent 100%);
        }

        .name {
          font-size: 32px;
          font-weight: 700;
          color: $gold-accent;
          letter-spacing: 2px;
          text-align: center;
          position: relative;
          padding: 0 20px;

          &::before,
          &::after {
            content: "";
            position: absolute;
            top: 50%;
            width: 6px;
            height: 6px;
            background: $gold-accent;
            border-radius: 50%;
            transform: translateY(-50%);
          }

          &::before {
            left: 0;
          }

          &::after {
            right: 0;
          }
        }
      }

      .products-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        grid-template-rows: repeat(2, 1fr);
        gap: 24px;
        padding: 0 100px;
        margin: 0 auto;

        .product-card-hover {
          border-radius: 4px;
        }
      }

      @media (max-width: 1024px) {
        .products-grid {
          grid-template-columns: repeat(3, 1fr);
          grid-template-rows: repeat(3, 1fr);
          gap: 20px;
        }

        .header .name {
          font-size: 28px;
        }
      }

      @media (max-width: 768px) {
        padding: 40px 0;

        .products-grid {
          grid-template-columns: repeat(2, 1fr);
          grid-template-rows: repeat(4, 1fr);
          gap: 16px;
          padding: 0 16px;
        }

        .header {
          margin-bottom: 30px;
          gap: 15px;

          .lines {
            width: 60px;
          }

          .name {
            font-size: 24px;
            letter-spacing: 1px;
          }
        }
      }

      @media (max-width: 480px) {
        .products-grid {
          grid-template-columns: 1fr;
          grid-template-rows: repeat(8, 1fr);
          gap: 12px;
        }

        .header .name {
          font-size: 20px;
        }
      }
    }
  }
}

.classify {
  padding: 0 min(160px, 8vw);
  margin-bottom: 40px;
  display: none;

  .container {
    width: 100%;
    margin: 0 auto;
  }

  .list {
    margin-top: 40px;
    border-radius: 16px;
    background: $pure-white;
    padding: 32px;
    transition: all 0.3s ease;

    .title {
      margin-bottom: 24px;
      padding-bottom: 24px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .name {
        font-size: 32px;
        color: $obsidian;
        font-weight: 700;
        letter-spacing: -0.5px;
      }

      .more {
        width: 44px;
        padding: 8px 16px;
        background: $ivory;
        border: 1px solid $slate;
        border-radius: 6px;
        color: $obsidian;
        font-size: 14px;
        font-weight: 600;
        letter-spacing: 2px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        text-decoration: none;
        grid-column: 4;
        margin-left: auto;

        &:hover {
          background: $slate;
          border-color: $slate;
          color: $obsidian;
          transform: translateY(-1px);
        }

        .iconfont {
          font-size: 12px;
          margin-left: 4px;
        }
      }
    }

    // 推广横幅样式
    .promotion-banner {
      margin-bottom: 80px;

      .wrapper_1200 {
        width: calc(100vw - 320px);
        max-width: none;
        margin: 0 auto;
        padding: 0;

        @media (max-width: 1520px) {
          width: calc(100vw - 160px);
        }

        @media (max-width: 1200px) {
          width: calc(100vw - 80px);
        }

        @media (max-width: 768px) {
          padding: 0 20px;
        }
      }

      .banner-item {
        display: flex;
        align-items: center;
        height: calc((100vw - 320px) * 0.27);
        min-height: 680px;
        background: $pure-white;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

        @media (max-width: 1520px) {
          height: calc((100vw - 160px) * 0.27);
        }

        @media (max-width: 1200px) {
          height: calc((100vw - 80px) * 0.27);
        }
      }

      .banner-link {
        display: flex;
        width: 100%;
        height: 100%;
        text-decoration: none;
        color: inherit;

        .banner-image {
          flex: 0 0 60%;
          height: 100%;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .banner-content {
          flex: 1;
          padding: calc(2vw + 48px);
          display: flex;
          flex-direction: column;
          justify-content: space-evenly;

          h3 {
            font-size: calc(1.5vw + 16px);
            font-weight: 700;
            color: $obsidian;
            margin-bottom: 40px;
            line-height: 1.2;
          }

          .banner-text {
            margin-bottom: 40px;
            display: flex;
            flex-direction: column;
            gap: 20px;
          }

          p {
            font-size: calc(0.8vw + 8px);
            color: $slate;
            line-height: 1.5;
          }

          .shop-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: calc(0.6vw + 6px) calc(1.2vw + 12px);
            background: $obsidian;
            color: white;
            border-radius: calc(0.4vw + 4px);
            font-size: calc(0.8vw + 8px);
            font-weight: 600;
            text-decoration: none;
            transition: all 0.3s ease;
            align-self: flex-start;
            cursor: pointer;
            white-space: nowrap;

            &:hover {
              background: $charcoal;
              transform: translateY(-2px);
            }
          }
        }

        @media (max-width: 768px) {
          flex-direction: column;

          .banner-image {
            flex: 0 0 200px;
          }

          .banner-content {
            padding: 24px;

            h3 {
              font-size: 24px;
            }

            p {
              font-size: 14px;
              margin-bottom: 20px;
            }
          }
        }
      }
    }

    // 响应式网格布局
    .acea-row {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 3rem 1.5rem;
      align-items: start;

      @media (max-width: 1200px) {
        grid-template-columns: repeat(3, 1fr);
      }

      @media (max-width: 900px) {
        grid-template-columns: repeat(2, 1fr);
        gap: 1.5rem 1rem;
      }

      @media (max-width: 600px) {
        grid-template-columns: 1fr;
        gap: 1.5rem;
      }
    }
  }
}
</style>
